<template>
  <div class="gallery-container">
    <!-- 图片网格 -->
    <div class="image-grid">
      <div
        v-for="(item, index) in currentPageItems"
        :key="index"
        class="image-card"
      >
        <!-- 图片带路由跳转 -->
        <router-link
          :to="getItemLink(item)"
          class="image-link"
        >
          <img
            :src="getImageUrl(item)"
            :alt="item.name"
            class="item-image"
            @error="handleImageError"
          >
        </router-link>

        <!-- 展开的数据行 - 2列布局 -->
        <div class="item-details">
          <div class="detail-column name-column">
            <span class="detail-label">名称:</span>
            <span class="detail-value">{{ item.name }}</span>
          </div>
          <div class="detail-column count-column">
            <span class="detail-label">数量:</span>
            <span class="detail-value">{{ item.count }}</span>
          </div>
        </div>
      </div>

      <!-- 空项填充，确保网格布局整齐 -->
      <div
        v-for="n in emptyItemsCount"
        :key="'empty-' + n"
        class="image-card empty-card"
      ></div>
    </div>

    <!-- 分页控制 -->
    <div class="pagination-controls">
      <button
        class="page-btn prev-btn"
        @click="prevPage"
        :disabled="currentPage === 1"
      >
        上一页
      </button>

      <span class="page-info">
        第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </span>

      <button
        class="page-btn next-btn"
        @click="nextPage"
        :disabled="currentPage === totalPages"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 每页显示的项目数量
const ITEMS_PER_PAGE = 8;

// 状态管理
const allItems = ref([]);
const currentPage = ref(1);
const totalItems = ref(0);
const user = ref('admin'); // 根据实际情况设置用户名

// 图片加载错误处理
const handleImageError = (e) => {
  // 加载失败时使用备用图片
  e.target.src = 'https://picsum.photos/200/200?grayscale';
  e.target.alt = '图片加载失败';
};

// 获取图片URL，如果接口返回为空则使用默认图
const getImageUrl = (item) => {
  if (item.img && item.img.trim() !== '' && item.img !== null) {
    const result = item.img.match(/[^/.]+(?=\.[^/.]+$)/)[0];

    return `http://localhost:8080/project/image/${result}`;
  }
  return `http://localhost:8080/project/image/default.jpg`;
};

// 生成项目链接
const getItemLink = (item) => {
  return `/webui/main2?context=${item.name}&user=${user.value}`;
};

// 从后端API获取数据
const fetchData = async (page = currentPage.value - 1) => {
  try {
    const response = await fetch(
      `http://localhost:8080/project/show?pageNum=${page}&pageSize=${ITEMS_PER_PAGE}`
    );
    const result = await response.json();

    // 检查接口返回状态
    if (result.code === 1) {
      allItems.value = result.msg.rows || [];
      totalItems.value = result.msg.total || 0; // 用后端返回的总条数，避免前端计算偏差
    } else {
      console.error('获取数据失败:', result.msg);
      allItems.value = [];
      totalItems.value = 0;
    }
  } catch (error) {
    console.error('请求出错:', error);
    allItems.value = [];
    totalItems.value = 0;
  }
};

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(totalItems.value / ITEMS_PER_PAGE);
});

// 获取当前页的项目
const currentPageItems = computed(() => allItems.value);

// 计算需要填充的空项数量
const emptyItemsCount = computed(() => {
  const remaining = ITEMS_PER_PAGE - currentPageItems.value.length;
  return remaining > 0 ? remaining : 0;
});

// 分页方法
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchData();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchData();
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.gallery-container {
  max-width: 1200px;
  margin: 2rem auto;
  padding: 0 1rem;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.gallery-title {
  color: #333;
  font-size: 1.8rem;
  text-align: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #f0f0f0;
}

/* 3行4列网格布局 */
.image-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.image-card {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.image-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
}

.empty-card {
  background-color: transparent;
  box-shadow: none;
}

.image-link {
  display: block;
  position: relative;
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.image-link:hover .item-image {
  transform: scale(1.05);
}

/* 详情部分 - 2列布局 */
.item-details {
  display: grid;
  grid-template-rows: 1fr 1fr; /* 行数 2 */
  grid-template-columns: 1fr; /* 列数 1 */
  padding: 0.8rem;
  gap: 0.5rem;
  background-color: #f9f9f9;
}

.detail-column {
  padding: 0.4rem;
}

.detail-label {
  font-size: 0.8rem;
  color: #666;
  margin-right: 0.3rem;
}

.detail-value {
  font-size: 0.9rem;
  font-weight: 500;
  color: #333;
}

.name-column .detail-value {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页控制 */
.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1.5rem;
  margin: 2rem 0;
}

.page-btn {
  padding: 0.6rem 1.2rem;
  border: none;
  border-radius: 4px;
  background-color: #4299e1;
  color: white;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: background-color 0.2s ease;
}

.page-btn:disabled {
  background-color: #cbd5e0;
  cursor: not-allowed;
  opacity: 0.7;
}

.page-btn:not(:disabled):hover {
  background-color: #3182ce;
}

.prev-btn {
  flex-direction: row-reverse;
}

.page-info {
  color: #4a5568;
  font-size: 1rem;
  font-weight: 500;
}

/* 响应式调整 */
@media (max-width: 1024px) {
  .image-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .image-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .item-image {
    height: 150px;
  }
}

@media (max-width: 480px) {
  .image-grid {
    grid-template-columns: 1fr;
  }

  .pagination-controls {
    gap: 0.8rem;
  }

  .page-btn {
    padding: 0.5rem 0.8rem;
    font-size: 0.9rem;
  }
}
</style>
